package com.lw.system.util.realm;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lw.common.constant.LogConstant;
import com.lw.common.constant.LoginConstant;
import com.lw.common.util.Encrypt;
import com.lw.system.model.User;
import com.lw.system.service.UserService;

public class ShiroDBRealm extends AuthorizingRealm {
	@Resource
	private UserService userService;

	private static final Logger LOG = LoggerFactory.getLogger(ShiroDBRealm.class);

	/**
	 * 
	 * 用户切换岗位时清除缓存的信息
	 * 
	 */
	@Override
	public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
		super.clearCachedAuthorizationInfo(principals);
	}

	@Override
	public AuthorizationInfo getAuthorizationInfo(PrincipalCollection principals) {
		return super.getAuthorizationInfo(principals);
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User u = (User) getAvailablePrincipal(principals);
		// 通过用户名去获得用户的所有资源，并把资源存入info中
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		Set<String> s = new HashSet<String>();
		s.add("p1");

		s.add("p2");
		info.setStringPermissions(s);
		Set<String> r = new HashSet<String>();
		r.add("r1");
		r.add("r2");
		info.setRoles(r);
		Subject currentUser = SecurityUtils.getSubject();
		LOG.info(LogConstant.LOG_MARK + u + "*********" + currentUser.getSession().getId());
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		/* 查询数据库 */
		User user = userService.findUserByLoginName(token.getUsername());
		if (user != null) {
			if (!LoginConstant.NORMAL_USER.equals(user.getStatus())) {
				throw new LockedAccountException(LoginConstant.LOCKED_ACCOUNT);
			}
			return new SimpleAuthenticationInfo(user.getLoginName(), user.getPassword().toCharArray(),
					ByteSource.Util.bytes(Encrypt.ENCRYPT_SALT.getBytes()), getName());
		} else {
			throw new UnknownAccountException("没有查到用户记录！");
		}

	}
}